<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\admin\model\user\UserMoneyLog as MoneyLogModel;
use app\admin\model\user\UserGoods;
use app\admin\model\litestore\Litestoregoods;
use Exception;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $salt = \fast\Random::alnum();
        $params['password'] = \app\common\library\Auth::instance()->getEncryptPassword($params['password'], $salt);
        $params['salt'] = $salt;

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 账户修改
     */
    public function up_money($ids)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post()['row'];
            //修改数据
            $row = $this->model->get(['id' => $data['id']]);
            $before = $row['money'];
            if($data['inc_dec'] == 1){
                $row->money = $before + abs($data['number']);
                $money = abs($data['number']);
            }else{
                $row->money = $before - abs($data['number']);
                if($row->money < 0){
                    $this->error(__('Insufficient Balance'));
                }
                $money = -abs($data['number']);
            }
            $row->save();

            //增加记录
            (new MoneyLogModel())->add_money_log($data['id'],$money,$before,$row->money,$data['memo']."(Admin id:".$this->auth->id.")");

            $this->success();
        }

        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 博主商品/商品库
     */
    public function blogger_goods($ids)
    {
        $this->assignconfig("ids", $ids);
        $this->view->assign("ids", $ids);
        return $this->view->fetch();
    }
    /**
     * 博主商品
     */
    public function table1($ids)
    {
        if ($this->request->isAjax()) {
            //设置过滤方法
            $this->request->filter(['strip_tags', 'trim']);
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $list = (new UserGoods())
                ->with(['goods'=>function($query){
                    return $query->withField('goods_id,goods_name,images');
                }])
                ->where('user_id','=',$ids)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)
                ->each(function($item){
                    $item->goods->image = cdnurl(explode(",",$item['goods']['images'])[0], true);
                });
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        $this->assignconfig("ids", $ids);
        $this->view->assign("ids", $ids);
        return $this->view->fetch('index');
    }
    /**
     * 商品库
     */
    public function table2($ids)
    {
        $this->model = model('\app\admin\model\litestore\Litestoregoods');
        if ($this->request->isAjax()) {
            $user_goods = (new UserGoods())->where('user_id','=',$ids)->column('goods_id');

            //设置过滤方法
            $this->request->filter(['strip_tags', 'trim']);
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $list = $this->model
                ->with(['category'])
                ->where("is_delete='0'")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)
                ->each(function($item)use($user_goods){
                    $item->image = cdnurl(explode(",",$item['images'])[0], true);
                    $item->name_p = get_parent_all($item->category_id);
                    if(in_array($item->goods_id,$user_goods)){
                        $item->choice = 10;
                    }else{
                        $item->choice = 20;
                    }
                });
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        $this->assignconfig("ids", $ids);
        $this->view->assign("ids", $ids);
        return $this->view->fetch('index');
    }

    /**
     * 修改佣金比例
     */
    public function up_rate($ids)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post()['row'];
            if($data['blogger_rate'] < 0 || $data['blogger_rate'] > 100){
                $this->error(__('Please enter 0~100'));
            }
            //修改数据
            $row = (new UserGoods())::get(['id' => $data['id']]);
            $row->blogger_rate = $data['blogger_rate'];
            $row->save();
            $this->success();
        }

        $row = (new UserGoods())::get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }
}
